<template>
  <div class="infobox">
    <div class="topbox">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <el-form-item>
            <!-- <el-button type="primary" @click="searchbutton">搜索</el-button> -->
            <el-button type="primary" @click="addbutton">新增</el-button>
            <el-button type="primary" @click="xgbutton">修改</el-button>
            <el-button type="primary" @click="deletebutton">删除</el-button>
          </el-form-item>
        </el-form-item>
      </el-form>
    </div>
    <div class="lbbox">
      <div class="titles">当前处方笺</div>
      <el-table :data="datalist" border max-height="500" @selection-change="handleSelectionChange">
        <el-table-column prop="medicineName" label="药品名" show-overflow-tooltip />
        <el-table-column prop="dosePerTime" label="每次剂量" show-overflow-tooltip />
        <el-table-column prop="prescriptionFrequency" label="处方频次" show-overflow-tooltip />
        <el-table-column prop="administrationMethod" label="服用方法" show-overflow-tooltip />
        <el-table-column prop="dosePerTime" label="每次剂量" show-overflow-tooltip />
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
      </el-table>
      <div class="titles">历史处方笺</div>
      <div class="lsboxs">
        <div v-for="(item, index) in datalistLS" :key="index" class="tablebox">
          <span class="textclass">记录人：{{ item.createBy }}</span>
          <span class="textclass">记录时间：{{ item.createTime }}</span>
          <el-table
            :data="item.tbPrescriptionHistoryDetailList"
            border
            max-height="500"
            @selection-change="handleSelectionChange"
          >
            <el-table-column prop="medicineName" label="药品名" show-overflow-tooltip />
            <el-table-column prop="dosePerTime" label="每次剂量" show-overflow-tooltip />
            <el-table-column prop="prescriptionFrequency" label="处方频次" show-overflow-tooltip />
            <el-table-column prop="administrationMethod" label="服用方法" show-overflow-tooltip />
            <el-table-column prop="dosePerTime" label="每次剂量" show-overflow-tooltip />
            <el-table-column prop="remark" label="备注" show-overflow-tooltip />
          </el-table>
        </div>
      </div>
      <!-- <div class="fybox">
        <el-pagination
          v-model:current-page="formInline.pageNum"
          v-model:page-size="formInline.pageSize"
          :page-sizes="[10, 50, 100, 200]"
          layout="total, sizes, prev, pager"
          :total="pagetotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div> -->
    </div>

    <el-dialog v-model="dialogVisible" title="详情" width="60%" :before-close="handleClose">
      <div class="infoboxtwo">
        <div class="searchbox">
          <el-card style="max-width: 300px" class="ypbox">
            <div>
              <el-input
                v-model="searchYPname"
                style="width: 240px"
                size="large"
                placeholder="搜索药品"
                :suffix-icon="Search"
                @change="remoteMethod"
              />
            </div>
            <div class="zsbox">
              <div @click="changeyp(o)" v-for="o in options" :key="o" class="ypitem">{{ o.medicineName }}</div>
            </div>
          </el-card>
        </div>
        <div class="tablebox">
          <el-table :data="tableData" border max-height="300">
            <el-table-column label="药品名" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.medicineName" />
              </template>
            </el-table-column>

            <el-table-column prop="address" label="每次剂量" align="center" width="120">
              <template #default="scope">
                <div class="mcjl">
                  <el-input v-model="scope.row.dosePerTime" />
                  <div class="dwbox"></div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="处方频次" align="center" width="120">
              <template #default="scope">
                <el-select v-model="scope.row.prescriptionFrequency">
                  <el-option v-for="item in cfpclist" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="服用方法" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.administrationMethodId">
                  <el-option v-for="item in yyztlist" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="备注" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.remark" />
              </template>
            </el-table-column>

            <el-table-column prop="address" label="操作" align="center" width="180">
              <template #default="scope">
                <el-button type="danger" @click="deletebuttontc(scope.row.medicineId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer savebox">
          <el-button type="primary" @click="addypbutton">新增药品</el-button>
          <el-button type="primary" @click="qkbutton">清空</el-button>
          <el-button type="primary" @click="savebuttontc">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogVisibletwo" title="详情" width="600" :before-close="handleCloseyp">
      <el-form :model="ruleForm" label-width="auto" ref="ruleFormRef" :rules="rules">
        <el-form-item label="药物名称" prop="medicineName">
          <el-input v-model="ruleForm.medicineName" />
        </el-form-item>

        <el-form-item label="备注" prop="medicineName">
          <el-input v-model="ruleForm.remark" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer savebox">
          <el-button @click="resetFormtwo(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="savebutton(ruleFormRef)"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getListcfxxApi,
  addcfxxAPI,
  getInfocfxxApi,
  updatecfxxAPI,
  deltecfxxApi,
  tag_now,
  tag_history
} from "@/api/hzmange/index.js";
import { seekdataApi, getyfListApi } from "@/api/system/system.js";
import { addypApi } from "@/api/system/system.js";
import { Search } from "@element-plus/icons-vue";
const route = useRoute();
const routedata = reactive(route.query);
let dialogVisible = ref(false);
let datalist = ref([]);
let datalistLS = ref([]);
const ruleFormRef = ref();
const updateList = ref({});
let dialogVisibletwo = ref(false);
let ruleForm = ref({});
const rules = reactive({
  projectName: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
  labTestItemId: [{ required: true, message: "请选择化验项", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  unit: [{ required: true, message: "请输入单位", trigger: "blur" }],
  remark: [{ required: true, message: "请输入备注", trigger: "blur" }]
});
const YZlist = JSON.parse(sessionStorage.getItem("YZlist"));
let yyztlist = ref([]); //服用方法
yyztlist.value = YZlist.sys_administration_method;
let searchYPname = ref("");
const options = ref([]);
const hylistoption = ref([]);

var pagetotal = ref(0);
let handleSizeChange = () => {
  getlist();
};
let handleCurrentChange = () => {
  getlist();
};
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  dialogVisible.value = false;
};
const searchbutton = () => {
  getlist();
};
const handleClose = done => {
  dialogVisible.value = false;
};
const addbutton = () => {
  xgstatus.value = false;
  tableData.value = [];
  dialogVisible.value = true;
};
let selection = ref([]);
const handleSelectionChange = e => {
  selection.value = e;
};
let nowid = ref(0);

const xgbutton = () => {
  getInfocfxxApi({
    id: nowid.value
  }).then(res => {
    dialogVisible.value = true;
    tableData.value = res.data.tbPrescriptionHistoryDetailList; //回显表格
    updateList.value = {
      id: res.data.id,
      remark: res.data.remark
    }; //修改表单数据
    xgstatus.value = true;
  });
};
const deletebutton = () => {
  if (selection.value.length == 1) {
    ElMessageBox.confirm("确定删除?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      deltecfxxApi({
        id: selection.value[0].id
      }).then(res => {
        ElMessage({
          type: "success",
          message: `${res.msg}`
        });
        getlist();
      });
    });
  } else {
    ElMessage({
      message: "请选择一条数据",
      type: "warning"
    });
  }
};
function savebuttontc() {
  let newadddata = {
    patientName: routedata.name, //患者姓名
    patientId: routedata.id, //患者ID
    tbPrescriptionHistoryDetailList: tableData.value
  };

  //修改
  if (xgstatus.value == true) {
    newadddata.id = updateList.value.id; //修改该条数据的id
    newadddata.remark = updateList.value.remark; //修改该条数据的备注
    updatecfxxAPI(newadddata).then(() => {
      ElMessage({
        message: "修改成功",
        type: "success"
      });
      dialogVisible.value = false;
      xgstatus.value = false;
      //刷新列表数据
      getlist();
    });
  } else {
    //新增
    addcfxxAPI(newadddata).then(() => {
      ElMessage({
        message: "新增成功",
        type: "success"
      });
      dialogVisible.value = false;
      getlist();
    });
  }
}
let formInline = ref({
  pageNum: 1,
  pageSize: 10,
  patientName: routedata.name, //患者姓名
  patientId: routedata.id //患者ID
});
getlist();
// 获取字典列表
function getlist() {
  tag_now({ patientId: routedata.id }).then(oneres => {
    console.log("1111111111111111", oneres.data);
    datalist.value = oneres.data.tbPrescriptionHistoryDetailList;
    nowid.value = oneres.data.id;
  });
  tag_history({ patientId: routedata.id }).then(twores => {
    console.log("2222222222222222222", twores.data);
    datalistLS.value = twores.data;
  });
  // datalist.rows = rows;
  // pagetotal.value = total;
}
let xgstatus = ref(false);
const loading = ref(false);
const remoteMethod = () => {
  let query = searchYPname.value;
  if (query) {
    loading.value = true;
    getyfListApi({
      pageNum: 1,
      pageSize: 10,
      medicineName: query
    }).then(res => {
      loading.value = false;
      let ypList = res.rows;
      options.value = ypList.filter(item => {
        return item.medicineName.toLowerCase().includes(query.toLowerCase());
      });
    });
  } else {
    options.value = [];
  }
};
var tableData = ref([]);
getYZlsit();
let cfpclist = ref([]); //处方频次
function getYZlsit() {
  seekdataApi({ dictType: "prescription_frequency" }).then(res => {
    cfpclist.value = res.data.map(item => ({
      value: item.dictValue,
      label: item.dictLabel
    }));
  });
}

let changeyp = e => {
  tableData.value.push({
    medicineName: e.medicineName, //药品名|商品名|规格
    medicineId: e.id, //药品id
    dosePerTime: "", //每次剂量
    prescriptionFrequency: "", //处方频次
    administrationMethodId: "1", //服用方法
    remark: "" //备注
  });
};
let deletebuttontc = e => {
  let idToDelete = e;
  tableData.value = tableData.value.filter(item => item.medicineId !== idToDelete);
};
let qkbutton = () => {
  tableData.value = [];
};
// 获取所有药品名称，用于显示在表格中
function getMedicineNames(medicineList) {
  if (!medicineList || medicineList.length === 0) return "";
  return medicineList.map(item => item.medicineName).join(", ");
}
// 获取所有药品信息，用于悬浮提示
function getMedicineTooltip(medicineList) {
  if (!medicineList || medicineList.length === 0) return "";
  return medicineList.map(item => item.medicineName).join("\n");
}
function savebutton() {
  //新增
  addypApi(ruleForm.value).then(() => {
    ElMessage({
      message: "新增成功",
      type: "success"
    });
    resetFormtwo();
  });
}
const resetFormtwo = () => {
  ruleForm.value = {};
  dialogVisibletwo.value = false;
};
function addypbutton() {
  console.log("11111111111111111111");
  dialogVisibletwo.value = true;
}
function handleCloseyp() {
  dialogVisibletwo.value = false;
}
</script>
<style lang="scss" scoped>
.lbbox {
  flex: 1;
}
.tablebox {
  width: calc(100% - 300px);
}

.ypbox {
  height: 100%;
}

.zsbox {
  width: 100%;
  height: 400px;
  padding: 0 20px;
  margin: 0 20px;
  overflow: auto;
}

.ypitem {
  cursor: pointer;
  margin: 15px 0;
}

.infobox {
  overflow: auto;
  display: flex;
  flex-direction: column;
}

.mcjl {
  display: flex;
}
.bottombox {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
}
.topbox {
  display: flex;

  margin-bottom: 10px;
}

.dwbox {
  margin-left: 5px;
}
.fybox {
  display: flex;
  justify-content: end;
}
.marginleft {
  margin-left: 5px;
}
.ypmcbox {
  width: 200px;
}
.topypbox {
  display: flex;
}
.infoboxtwo {
  width: 100%;
  display: flex;
}
.searchbox {
  margin-right: 10px;
}
.ywbox {
  margin: 0 8px;
}
.tablebox {
  margin: 15px 0;
}
.titles {
  font-weight: bold;
  margin-bottom: 5px;
  color: #606266;
}
.textclass {
  font-size: 14px;
  margin-bottom: 5px;
  color: #6587ca;
}
.lsboxs {
  overflow: auto;
  height: 400px;
}
</style>
